package com.example.weight.greenSeasons.waterDeal;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class WaterTreatmentTable_old extends AppCompatActivity implements View.OnClickListener{
    //now date
    private Date useElectricityDate = new Date(System.currentTimeMillis());

    //date formatter
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private TitleBar titleBar;
    private TextView treatment_date,treatment_time,discharge_start,discharge_end,remarks;
    private EditText old_flow_count,new_flow_count,total_flow_count,pool_level,instantaneous_flow,alkali_dosage_A,alkali_dosage_O;
    private Button btn_discharge_start,btn_discharge_end;
    private String factory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent previousIntent = getIntent();
        factory = previousIntent.getStringExtra("factory");

        setContentView(R.layout.activity_water_treatment_table_old);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                WaterTreatmentTable_old.this.finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }


        });
        instantaneous_flow=findViewById(R.id.instantaneous_flow);
        alkali_dosage_A=findViewById(R.id.alkali_dosage_A);
        alkali_dosage_O=findViewById(R.id.alkali_dosage_O);
//        日期时间
        treatment_date=findViewById(R.id.treatment_date);
        treatment_time=findViewById(R.id.treatment_time);
        treatment_date.setText(simpleDateFormat.format(useElectricityDate));
        simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
        treatment_time.setText(simpleDateFormat1.format(useElectricityDate));

//        treatment_time.setOnClickListener(this/);
//        流量计读数
        old_flow_count=findViewById(R.id.old_flow_count);
        new_flow_count=findViewById(R.id.new_flow_count);
        total_flow_count=findViewById(R.id.total_flow_count);
        pool_level=findViewById(R.id.pool_level);
//        排泥起止时间
        discharge_start=findViewById(R.id.discharge_start);
        discharge_end=findViewById(R.id.discharge_end);
        btn_discharge_start=findViewById(R.id.btn_discharge_start);
        btn_discharge_end=findViewById(R.id.btn_discharge_end);
        discharge_start.setOnClickListener(this);
        discharge_end.setOnClickListener(this);
        btn_discharge_start.setOnClickListener(this);
        btn_discharge_end.setOnClickListener(this);
//        备注
        remarks=findViewById(R.id.remarks);
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/sjq/sjqWaterProductionElectricityConsumption/findForm";
        String url = Config.url + "/sjq/SjqWaterProcess/getLast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            Date fromDate_treatment_time = new Date();
                            Date fromDate_discharge_start = new Date();
                            Date fromDate_discharge_end = new Date();
                            try {
                                fromDate_treatment_time = simpleDateFormat1.parse(data.getString("time").split(" ")[1]);
                                simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
                                fromDate_discharge_start = simpleDateFormat1.parse(data.getString("soilDischargingStartTime"));
                                simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
                                fromDate_discharge_end = simpleDateFormat1.parse(data.getString("soilDischargingEndTime"));
                                simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
                            } catch (java.text.ParseException e) {
                                e.printStackTrace();
                            }
                            if (!data.isNull("id") && data.getString("factory").equals(factory)) {
//                                treatment_time.setText(simpleDateFormat1.format(fromDate_treatment_time));
                                simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
                                old_flow_count.setText(data.getString("flowMeterReading1"));
                                new_flow_count.setText(data.getString("flowMeterReading2"));
                                total_flow_count.setText(data.getString("flowMeterReadingTotal"));
                                pool_level.setText(data.getString("oLevel"));
                                discharge_start.setText(simpleDateFormat1.format(fromDate_discharge_start));
                                discharge_end.setText(simpleDateFormat1.format(fromDate_discharge_end));
                                remarks.setText(data.getString("remarks"));
//                                btn_discharge_start.setEnabled(false);
//                                btn_discharge_end.setEnabled(false);
                                instantaneous_flow.setText(data.getString("instantaneousFlow"));
                                alkali_dosage_A.setText(data.getString("alkaliDosageA"));
                                alkali_dosage_O.setText(data.getString("alkaliDosageO"));
                                Toast.makeText(WaterTreatmentTable_old.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(WaterTreatmentTable_old.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.treatment_time:
                showTimePickerDialog(this,  2, treatment_time, calendar);;
                break;
            case R.id.btn_discharge_start:
                Date date_1_start = new Date(System.currentTimeMillis());
                String s_1_start = simpleDateFormat1.format(date_1_start);
                discharge_start.setText(s_1_start);
                btn_discharge_start.setEnabled(false);
                break;
            case R.id.btn_discharge_end:
                Date date_1_end = new Date(System.currentTimeMillis());
                String s_1_end = simpleDateFormat1.format(date_1_end);
                discharge_end.setText(s_1_end);
                btn_discharge_end.setEnabled(false);
                break;
            case R.id.discharge_start:
                showTimePickerDialog(this,  2, discharge_start, calendar);
                break;
            case R.id.discharge_end:
                showTimePickerDialog(this,  2, discharge_end, calendar);;
                break;
            default:
                break;
        }
    }
    public void save(View view) {
        if (old_flow_count.getText().toString().equals("")) {
            Toast.makeText(this, "请填写(旧膜)流量计读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (new_flow_count.getText().toString().equals("")) {
            Toast.makeText(this, "请填写(新膜)流量计读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (total_flow_count.getText().toString().equals("")) {
            Toast.makeText(this, "请填写总流量计读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (instantaneous_flow.getText().toString().equals("")) {
            Toast.makeText(this, "请填写瞬时流量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (alkali_dosage_A.getText().toString().equals("")) {
            Toast.makeText(this, "请填写A池加碱量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (alkali_dosage_O.getText().toString().equals("")) {
            Toast.makeText(this, "请填写O池加碱量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (pool_level.getText().toString().equals("")) {
            Toast.makeText(this, "请填写O池液位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (discharge_start.getText().toString().equals("")) {
            Toast.makeText(this, "请选择排泥开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (discharge_end.getText().toString().equals("")) {
            Toast.makeText(this, "请选择排泥结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/SjqWaterProcess/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
//                                    Toast.makeText(WaterTreatmentTable_old.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(WaterTreatmentTable_old.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(WaterTreatmentTable_old.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(WaterTreatmentTable_old.this,
                                    "保存失败2" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            String time = treatment_date.getText().toString()+" "+treatment_time.getText().toString();
                            map.put("time", time);
                            map.put("instantaneous_flow", instantaneous_flow.getText().toString());
                            map.put("flow_meter_reading_1", old_flow_count.getText().toString());
                            map.put("flow_meter_reading_2", new_flow_count.getText().toString());
                            map.put("flow_meter_reading_total",total_flow_count.getText().toString());
                            map.put("o_level", pool_level.getText().toString());
                            map.put("soil_discharging_start_time", discharge_start.getText().toString());
                            map.put("soil_discharging_end_time", discharge_end.getText().toString());
                            map.put("alkali_dosage_A", alkali_dosage_A.getText().toString());
                            map.put("alkali_dosage_O", alkali_dosage_O.getText().toString());
                            map.put("remarks", remarks.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }

}